#encoding:utf-8
'''
Created on Sep 9, 2014

@author: liuxue
'''
#encoding:utf-8
'''
Created on 2012-5-18

@author: Liuxue
'''

from logging import getLogger
import os

from mako.lookup import TemplateLookup
from mako.template import Template
import tornado.httpserver
import tornado.ioloop
from tornado.web import StaticFileHandler, url
import tornado.web
from tornado.template import Template as TTemplate

from handlers.basehandler import BaseRequestHandler
import logging.config
from services.baseservice import BaseService
from services.otherservice import ProcessService


DEBUG = True
settings = {'debug':DEBUG,
            'template_path':os.path.join(os.path.dirname(__file__), "templates"),
            'static_path': 'static',
            'mako_templates_lookup':[os.path.join(os.path.dirname(__file__), "templates")],
            }
    
app = {
       'base': BaseService,
       'process': ProcessService,
       }

class GatewayHandler(BaseRequestHandler):
    def get(self):
        method = self.g('method', 'base')
        
        service = app[method](self)
        
        self.write(service.process())
        
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('demo_index.html')

class IndexXHandler(tornado.web.RequestHandler):
    def get(self, x):
        print(x)
        print(self.request)
        self.render('demo_index.html')

class MakoHandler(tornado.web.RequestHandler):
    
    _lookup = TemplateLookup(settings.get('mako_templates_lookup', []))#这里是模板的路径  这么设置它会在templates文件夹下查找模板

    def render_string(self, filename, **kwargs):
        '''Override render_string to use mako template.
        
        Like tornado render_string method, this method
        also pass request handler environment to template engine.
        '''
        try:
            template = self._lookup.get_template(filename)
            env_kwargs = self.get_template_namespace()
            t0 = template.render(**kwargs)
            t = TTemplate(t0).generate(**env_kwargs)
            return t
        except Exception as e:
            # exception handler
            getLogger('tornado.application').exception(e)
        
    def get(self):
        self.render('demo_mako.html', title='mako')


apps = [
        
        url(r"/demo/index", IndexHandler, name="index"),
        url(r"/demo/indexx/([a-z]+)/", IndexXHandler, name="index_x"),
        (r"/demo/mako", MakoHandler),
        (r"/static/(.*)", StaticFileHandler, {"path": "static"})
        ]
    
application = tornado.web.Application(apps, **settings)

def initial_all(args):
    config_dict = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(name)s %(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },

    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'logging.NullHandler',
        },
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename':'demo.log',
        }
    },
    'loggers': {
        'root': {
            'handlers':['console'],
            'propagate': True,
            'level':'DEBUG',
        },
        'tornado.access': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
    'tornado.application': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
    'tornado.general': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
    }
   }
    logging.config.dictConfig(config_dict)

    
    
def check_app():
    for k, s in app.items():
        service = s(None)
        assert k == service.name, '%s diff %s'%(k, service.__class__.__name__)

def startup(port=9090):
    server = tornado.httpserver.HTTPServer(application)
    server.listen(port)
    getLogger('tornado.application').info('tornado start')
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    initial_all(None)
    
    check_app()
    # start the http service
    startup(8080)